package cmd

import (
	"fmt"

	"github.com/graphql-go/graphql"
)

// 定义用户类型
var userType = graphql.NewObject(graphql.ObjectConfig{
	Name: "User",
	Fields: graphql.Fields{
		"id": &graphql.Field{
			Type: graphql.Int,
		},
		"name": &graphql.Field{
			Type: graphql.String,
		},
		"age": &graphql.Field{
			Type: graphql.Int,
		},
	},
})

// 模拟用户数据
var users = []map[string]interface{}{
	{"id": 1, "name": "张三", "age": 25},
	{"id": 2, "name": "李四", "age": 30},
}

// 定义查询
var rootQuery = graphql.NewObject(graphql.ObjectConfig{
	Name: "RootQuery",
	Fields: graphql.Fields{
		"user": &graphql.Field{
			Type: userType,
			Args: graphql.FieldConfigArgument{
				"id": &graphql.ArgumentConfig{
					Type: graphql.Int,
				},
			},
			Resolve: func(p graphql.ResolveParams) (interface{}, error) {
				id, ok := p.Args["id"].(int)
				if ok {
					for _, user := range users {
						if int(user["id"].(int)) == id {
							return user, nil
						}
					}
				}
				return nil, nil
			},
		},
		"users": &graphql.Field{
			Type: graphql.NewList(userType),
			Resolve: func(p graphql.ResolveParams) (interface{}, error) {
				fmt.Println("Args", p.Args)
				fmt.Println("Info", p.Info)
				fmt.Println("Source", p.Source)
				return users, nil
			},
		},
	},
})

// 创建模式
var schema, _ = graphql.NewSchema(graphql.SchemaConfig{
	Query: rootQuery,
})
